package stanford.com.balldating.chat;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import stanford.com.balldating.util.HttpClientUtils;
import stanford.com.balldating.util.UserUtils;

public class ChatService extends Service {
    public static final String RECEIVE_MESSAGE="stanford.com.balldating.chat.ChatService.receiveMessage";
    public static final String SEND_MESSAGE="stanford.com.balldating.chat.ChatService.sendMessage";

    private static WebSocketClient mWebSocketClient;
    public static HashMap<String,List<ChatMessage>> friends=new HashMap<>();

    private BroadcastReceiver receiver;

    public ChatService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if(mWebSocketClient!=null) {
            mWebSocketClient.close();
        }
        try {
            URI uri = new URI(HttpClientUtils.WEBSOCKET_URL + "?username=" + UserUtils.getUser().getname());
            mWebSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                }

                @Override
                public void onMessage(String s) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        ChatMessage msg = new ChatMessage(jsonObject);
                        List<ChatMessage> messages = friends.get(msg.from);
                        if (messages == null) {
                            messages = new ArrayList<>();
                            friends.put(msg.from, messages);
                        }
                        messages.add(msg);

                        Intent it = new Intent(RECEIVE_MESSAGE);
                        it.putExtra("msg", msg);
                        sendBroadcast(it);
                    } catch (Exception e) {
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            };

            mWebSocketClient.connect();
        }catch (Exception e){}

        IntentFilter counterActionFilter = new IntentFilter(ChatService.SEND_MESSAGE);
        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ChatMessage message=(ChatMessage)intent.getSerializableExtra("msg");
                if(mWebSocketClient!=null&&mWebSocketClient.isOpen()){
                    try{
                        mWebSocketClient.send(message.toJSONObject().toString());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        };
        registerReceiver(receiver, counterActionFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if(mWebSocketClient!=null){
            mWebSocketClient.close();
            mWebSocketClient=null;
        }
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
